package com.example.playnote.activity.ui

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.KeyEvent
import android.view.Menu
import android.view.MenuItem
import android.widget.LinearLayout
import com.example.playnote.R
import com.example.playnote.activity.login.LoginActivity
import com.example.playnote.base.BaseActivity
import com.example.playnote.bean.Constant
import com.example.playnote.bean.ToastFlag
import com.example.playnote.databinding.ActivityContentBinding
import com.example.playnote.getAgentWeb
import com.example.playnote.toasty
import com.example.playnote.utils.MMKVUtils
import com.example.playnote.viewModel.HomeViewModel
import com.just.agentweb.AgentWeb
import es.dmoral.toasty.Toasty

class ContentActivity: BaseActivity<HomeViewModel,ActivityContentBinding>() {
    private lateinit var agentWeb: AgentWeb
    private lateinit var shareTitle: String
    private lateinit var shareUrl: String
    private var shareId: Int = 0
    private var isAdd: Boolean = true
    /**
     * check login for SharedPreferences
     */
    private val isLogin: Boolean by lazy {
        MMKVUtils.getBoolean(Constant.LOGIN_KEY) ?: false
    }

    override fun initImmersionBar() {
        super.initImmersionBar()
        immersionBar.titleBar(mDatabind.toolbar).init()
    }

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.toolbar.run {
            title = getString(R.string.loading)
            setSupportActionBar(this)
            supportActionBar?.setDisplayHomeAsUpEnabled(true)
        }
        intent.extras?.let {
            shareId = it.getInt(Constant.CONTENT_ID_KEY, 0)
            shareUrl = it.getString(Constant.CONTENT_URL_KEY, "")
            shareTitle = it.getString(Constant.CONTENT_TITLE_KEY, "")
            agentWeb = shareUrl.getAgentWeb(
                this,
                mDatabind.webContent,
                LinearLayout.LayoutParams(-1, -1),
            )
        }
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.menu_content, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            android.R.id.home -> {
                finish()
                return true
            }
            R.id.menuShare -> {
                Intent().run {
                    action = Intent.ACTION_SEND
                    putExtra(
                        Intent.EXTRA_TEXT,
                        getString(
                            R.string.share_article_url,
                            getString(R.string.app_name),
                            shareTitle,
                            shareUrl
                        )
                    )
                    type = Constant.CONTENT_SHARE_TYPE
                    startActivity(Intent.createChooser(this, getString(R.string.share_title)))
                }
                return true
            }
            R.id.menuLike -> {
                // login
                if (!isLogin) {
                    Toasty.error(this,R.string.login_please_login,Toasty.LENGTH_SHORT).show()
                    Intent(this, LoginActivity::class.java).run {
                        startActivity(this)
                    }
                    return true
                }
                // Collection outside article
                if (shareId == 0) {
                    mViewModel.collectOutSideArticle(
                        shareTitle,
                        getString(R.string.outside_title),
                        shareUrl,
                        true
                    )
                    return true
                }
                // Collection station article
                mViewModel.collectArticle(shareId, true)
                return true
            }
            R.id.menuBrowser -> {
                Intent().run {
                    action = "android.intent.action.VIEW"
                    data = Uri.parse(shareUrl)
                    startActivity(this)
                }
                return true
            }
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onPause() {
        agentWeb.webLifeCycle.onPause()
        super.onPause()
    }

    override fun onResume() {
        agentWeb.webLifeCycle.onResume()
        super.onResume()
    }

    override fun onDestroy() {
        agentWeb.webLifeCycle.onDestroy()
        super.onDestroy()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        return if (agentWeb.handleKeyEvent(keyCode, event)) {
            true
        } else {
            finish()
            super.onKeyDown(keyCode, event)
        }
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.outSideArticle.observe(this) {
            val type = if (it.errorCode != 0) ToastFlag.ERROR else ToastFlag.SUCCESS
            val content = if (it.errorCode != 0) getString(R.string.bookmark_cancel_failed, it.errorMsg) else getString(R.string.bookmark_success)
            this.toasty(type, content)
        }
    }
}